package com.example.apricots.db;

import android.util.Log;

import com.example.apricots.Base.App;
import com.example.apricots.bean.User;
import com.example.apricots.bean.greendao.UserDao;

import java.util.List;

/**
 * 数据库操作类
 */
public class DBManager {
    private static final String TAG = DBManager.class.getSimpleName();
    private static final DBManager instance = new DBManager();


    public static DBManager getInstance() {
        return instance;
    }

    /**
     * 增加用户(用户注册)
     *
     * @param u user
     */
    public void AddUser(User u) {
        if (u == null) {
            return;
        }
        UserDao userDao = App.getInstance().getDaosession().getUserDao();
        userDao.insert(u);
        Log.e(TAG, "AddUser: success");
    }

    /**
     * 更新用户
     *
     * @param
     */
    public void updateUserByPwd(String pwd_old, String pwd_new) {
        User user = null;
        UserDao userDao = App.getInstance().getDaosession().getUserDao();
        List<User> userList = userDao.queryBuilder()
                .where(UserDao.Properties.Password.eq(pwd_old))
                .build()
                .list();
        if (userList.size() > 0) {
            user = userList.get(0);
        }
        if (user != null) {
            user.setPassword(pwd_new);
        }
        userDao.update(user);
        Log.e(TAG, "updateUserByPwd: 更新密码成功");
    }



    /**
     * 删除用户
     *
     * @param u user
     */
    public void deleteUser(User u) {
        UserDao userDao = App.getInstance().getDaosession().getUserDao();
        userDao.deleteByKey(u.getId());
        Log.e(TAG, "deleteUser: success");
    }


    /**
     * 查询用户
     *
     * @param username username
     */
    public List<User> queryUserByUsername(String username) {
        //List<User> userList=new ArrayList<>();
        UserDao userDao = App.getInstance().getDaosession().getUserDao();
        List<User> userLists = userDao.queryBuilder().where(UserDao.Properties.Username.eq(username)).list();
        if (userLists.isEmpty() || userLists.size() == 0) {
            Log.e(TAG, "queryUser user is null ");
            return null;
        }
        Log.e(TAG, "queryUser: success");
        return userLists;

    }

    /**
     * 查询用户
     */
    public List<User> queryUser() {
        //List<User> userList=new ArrayList<>();
        UserDao userDao = App.getInstance().getDaosession().getUserDao();
        List<User> userLists = userDao.queryBuilder().list();
        if (userLists.isEmpty() || userLists.size() == 0) {
            Log.e(TAG, "queryUser user is null ");
            return null;
        }
        Log.e(TAG, "queryUser: success");
        return userLists;

    }

}
